package org.springblade.common.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.SecureUtil;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @Description:
 * @Author: yangyunjiang
 * @Date: 2022/3/25 13:44
 */
@Component
public class MetaHandler implements MetaObjectHandler {

	/**
	 * 新增数据执行
	 */
	@Override
	public void insertFill(MetaObject metaObject) {
		boolean hasSetter = metaObject.hasSetter("createTime");
		if (hasSetter) {
			this.setFieldValByName("createTime", new Date(), metaObject);
			this.setFieldValByName("updateTime", new Date(), metaObject);
		}
		boolean createBy = metaObject.hasSetter("createBy");
		if (createBy) {
			BladeUser bladeUser = SecureUtil.getUser();
			if (bladeUser!=null){
				this.setFieldValByName("createBy", bladeUser.getUserId(), metaObject);
				this.setFieldValByName("createByName", bladeUser.getUserName(), metaObject);
			}else{
				this.setFieldValByName("createByName", "system", metaObject);
			}
		}
	}

	/**
	 * 更新数据执行
	 */
	@Override
	public void updateFill(MetaObject metaObject) {
		boolean hasSetter = metaObject.hasSetter("updateTime");
		if (hasSetter) {
			this.setFieldValByName("updateTime", new Date(), metaObject);
		}
		boolean updateBy = metaObject.hasSetter("updateBy");
		if (updateBy) {
			BladeUser bladeUser = SecureUtil.getUser();
			if (bladeUser!=null){
				this.setFieldValByName("updateBy", bladeUser.getUserId(), metaObject);
				this.setFieldValByName("updateByName", bladeUser.getUserName(), metaObject);
			}else{
				this.setFieldValByName("updateByName", "system", metaObject);
			}
		}
	}

}
